Component({
  options: {
    multipleSlots: true,
    addGlobalClass: true
  },
  properties: {
    count: {
      type: Number,
      value: 1
    },
    limitNum: {
      type: Number,
      value: 0
    },
    stockNum: {
      type: Number,
      value: 0
    },
    zero: {
      type: Boolean,
      value: false
    },
    disable: {
      type: Boolean,
      value: false
    },

  },
  observers: {
    'count': function (count) {
      this.setData({showNum: Number(count)})
    }
  },
  data: {
    showNum: 0,
    timeoutId: null
  },
  methods: {
    handleInput(event) {
      let val = event.detail.value;
      if (val === this.data.count) {
        return;
      }
      if (this.data.limitNum !== 0 && val > this.data.limitNum) {
        wx.showToast({title: "超出最大购买数量", icon: "none", duration: 2000});
        this.setData({showNum: this.data.count});
        return;
      }
      if (val <= 0) {
        wx.showToast({title: "购买数量必须大于零", icon: "none", duration: 2000});
        this.setData({showNum: this.data.count});
        return;
      }
      this.setData({showNum: Number(val)})
      this.triggerEvent('update', {num: Number(val)});
    },
    handleAdd() {
      if (this.data.disable) {
        return;
      }
      let showNum = this.data.showNum

      if (this.data.limitNum !== 0 && showNum + 1 > this.data.limitNum) {
        wx.showToast({title: "超出最大购买数量", icon: "none", duration: 2000});
        return;
      }
      if (this.data.stockNum !== 0 && showNum + 1 > this.data.stockNum) {
        wx.showToast({title: "商品库存不足", icon: "none", duration: 2000});
        return;
      }
      showNum = showNum + 1
      this.setData({showNum: showNum});
      // 限流
      this.throttleEvent(showNum);
    },

    handleSubtract() {
      if (this.data.disable) {
        return;
      }
      let showNum = this.data.showNum
      if (showNum - 1 <= 0) {
        wx.showToast({
          title: '该商品不能减少了噢',
          icon: 'none'
        })
        return;
      }
      showNum = showNum - 1
      this.setData({showNum: showNum});
      this.throttleEvent(showNum);
    },
    throttleEvent(showNum) {
      let timeoutId = this.data.timeoutId
      if (timeoutId) {
        this.setData({timeoutId: null})
        clearTimeout(timeoutId);
      }
      timeoutId = setTimeout(() => {
        this.triggerEvent('update', {num: showNum});
      }, 100)
      this.setData({timeoutId: timeoutId})
    }
  }
});
